import router from './router'
import Layout from './layout'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar (绿色的进度条)
import 'nprogress/nprogress.css' // progress bar style
import menuSetting from '@/menuSet.js'
import { getToken, getUserName, getHomeRouter } from '@/utils/validate.js'

const title = menuSetting.title || '菜单'
function getPageTitle(pageTitle) {
  if (pageTitle) {
    return `${pageTitle} - ${title}`
  }
  return `${title}`
}

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist 没有重定向的白色名单

router.beforeEach(async(to, from, next) => {
  NProgress.start()

  // 设置登录时的菜单
  document.title = getPageTitle(to.meta.title)
  // console.log('设置登录时的菜单', document.title)
  if (getToken()) {
    if (to.path === '/login') {
      // 如果已登录，则重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoles = store.state.permission.routesList && store.state.permission.routesList.length > 0
      if (hasRoles || menuSetting.isLocalRouter) {
        next()
      } else {
        store
          .dispatch('permission/getRoutesMenu')
          .then(accessRoutes => {
            // 登录成功后设置标题跟门店
            store.dispatch('user/SetUserName', getUserName())
            // 设置路由跟菜单
            const arrRouter = [
              {
                path: '/',
                redirect: JSON.parse(getHomeRouter()).path,
                hidden: true,
                component: Layout,
                children: accessRoutes
              },
              { path: '*', redirect: '/404', hidden: true }
            ]
            router.addRoutes(arrRouter) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
          .catch(() => {
            store.dispatch('user/FedLogOut').then(err => {
              Message({
                message: err,
                type: 'error'
              })
              next({ path: '/' })
            })
          })
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
